/*
 * @Author       : xh
 * @Date         : 2022-10-17 14:20:12
 * @LastEditors: y001554
 * @FileName     :
 */
const fsExtra = require('fs-extra')
const path = require('path')
const fs = require('fs')
const { defineConfig, build } = require('vite')
const vue = require('@vitejs/plugin-vue')
const vueJsx = require('@vitejs/plugin-vue-jsx')

const entryDir = path.resolve(__dirname, '../../mini_ui')
const outputDir = path.resolve(__dirname, '../../build')

const baseConfig = defineConfig({
  configFile: false,
  publicDir: false,
  plugins: [vue(), vueJsx()]
})
const rollupOptions = {
  external: ['vue', 'vue-router', 'element-plus'],
  output: {
    globals: {
      vue: 'Vue'
    }
  }
}

// 单组件按需构建
const buildSingle = async (name) => {
  await build(
    defineConfig({
      ...baseConfig,
      build: {
        rollupOptions,
        lib: {
          entry: path.resolve(entryDir, name),
          name: 'index',
          fileName: 'index',
          formats: ['es', 'umd']
        },
        outDir: path.resolve(outputDir, name)
      }
    })
  )
}

// 生成组件的 package.json 文件
const createPackageJson = (name) => {
  const fileStr = `{
  "name": "${name}",
  "version": "0.0.0",
  "main": "index.umd.js",
  "module": "index.js",
  "style": "style.css"
}`

  fsExtra.outputFile(
    path.resolve(outputDir, `${name}/package.json`),
    fileStr,
    'utf-8'
  )
}

const buildLib = async () => {
  // 获取组件名称组成的数组
  const components = fs.readdirSync(entryDir).filter((name) => {
    const componentDir = path.resolve(entryDir, name)
    const isDir = fs.lstatSync(componentDir).isDirectory()
    return isDir && fs.readdirSync(componentDir).includes('index.ts')
  })

  // 循环一个一个组件构建
  for (const name of components) {
    // 构建单组件
    await buildSingle(name)

    // 生成组件的 package.json 文件
    createPackageJson(name)
  }
  // createIndexPackageJson(components)
}

// //创建一个 中的index 入口的引用文件
// createIndexPackageJson = components => {
//   console.log('口的引用文件', components)

//   const fileStr = `

//   import  { Button } from './button/index.js'

//   const installs = [
//     Button,
//   ]
//   export {
//     Button,
//   }

//   export default {
//     version: '0.0.1',
//     install(app) {
//       installs.forEach((p) => app.use(p))
//     }
//   }`

//   fsExtra.outputFile(
//     path.resolve(outputDir, `index.js`),
//     fileStr,
//     'utf-8'
//   )
// }

buildLib()
